/*!
 * Copyright 2018 Hitachi Vantara. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Defines the database connection loading component
 */
define([
  'text!./loading.html',
  'pentaho/i18n-osgi!repositories-plugin.messages',
  'css!./loading.css'
], function (template, i18n) {

  'use strict';

  var options = {
    bindings: {
      connection: "="
    },
    controllerAs: "vm",
    template: template,
    controller: loadingController
  };

  loadingController.$inject = ["loadingService", "$state", "$timeout"];

  /**
   * The controller for the database connection loading component
   *
   * @param {Object} loadingService - service for adding/updating the database connection
   * @param {Object} $state - object for controlling the app state
   * @param {Function} $timeout - function for setting timeout
   */
  function loadingController(loadingService, $state, $timeout) {
    var vm = this;
    vm.$onInit = onInit;

    /**
     * The $onInit hook of components lifecycle which is called on each controller
     * after all the controllers on an element have been constructed and had their
     * bindings initialized. We use this hook to put initialization code for our controller.
     */
    function onInit() {
      if (vm.connection.edit || vm.connection.modify) {
        vm.message = i18n.get('repositories.loading.updating.label') + " " + vm.connection.displayName + ".";
        $timeout(function() {
          loadingService.updateRepository(vm.connection).then(function () {
            $state.go("database.success");
          }, function (err) {
            $state.go("database.failure");
          });
        }, 1000);
      } else {
        vm.message = i18n.get('repositories.loading.creating.label') + " " + vm.connection.displayName + ".";
        $timeout(function() {
          loadingService.addRepository(vm.connection).then(function(){
            $state.go("database.success");
          }, function(err) {
            $state.go("database.failure");
          });
        }, 1000);
      }
    }
  }

  return {
    name: "database.loading",
    options: options
  };

});
